package sg.edu.nus.iss.jass.gui.component;

import javax.swing.JTextField;

import sg.edu.nus.iss.jass.exception.ValidationException;
import sg.edu.nus.iss.jass.validation.FormValidator;
import sg.edu.nus.iss.jass.validation.ValidationRule;
import sg.edu.nus.iss.jass.validation.Validator;

public class ValidateJTextField extends JTextField {
	
	private ValidationRule[] rules;
	private String fieldName;
	private boolean isUpperCase;
	private Validator validator;
	
	public ValidateJTextField(String fieldName, ValidationRule ... rules){
		this.fieldName = fieldName;
		this.rules = rules; 
	}
	
	public ValidateJTextField(String fieldName, Validator validator) {
		this.fieldName = fieldName;
		this.validator = validator;
	}
	
	public void setFieldName(String myFieldName) {
		this.fieldName = myFieldName;
	}
	
	public void setRules(ValidationRule ... rules) {
		this.rules = rules;
	}
	
	public String getValidatedText() throws ValidationException{
		if (this.validator == null) {
			if(this.isEditable())
				FormValidator.validate(this.fieldName, this.getText(), rules);
			if(isUpperCase)
				return this.getText().toUpperCase();
			else
				return this.getText();
		} else {
			if (this.isEditable())
				this.validator.validate(fieldName);
			return this.getText();
		}
	}

	public void clearText(){
		this.setText("");
	}
}